package Sync;

import java.io.*;
import java.net.Socket;

public class SharedSocket {
    private final Socket socket;
    private int referenceCount = 0;
    private boolean shouldStopSending = false;
    // 添加用于线程间通信的对象锁
    private final Object sendLock = new Object();

    public SharedSocket(Socket socket) {
        this.socket = socket;
    }

    public synchronized void increment() {
        referenceCount++;
    }

    public synchronized void decrement() {
        referenceCount--;

        if (referenceCount <= 0) {
            try { socket.close(); } catch (IOException ignored) {}
        }
    }

    public InputStream getInputStream() throws IOException {
        return socket.getInputStream();
    }

    public OutputStream getOutputStream() throws IOException {
        return socket.getOutputStream();
    }

    /**
     * 获取当前 SharedSocket 实例的引用计数
     *
     * @return 当前引用计数
     */
    public synchronized int getReferenceCount() {
        return referenceCount;
    }

    /**
     * 发送线程等待方法
     * @throws InterruptedException 如果线程在等待时被中断
     */
    public void waitForSend() throws InterruptedException {
        synchronized (sendLock) {
            sendLock.wait();
        }
    }

    /**
     * 接收线程唤醒发送线程的方法
     */
    public void notifySend() {
        synchronized (sendLock) {
            sendLock.notify();
        }
    }

    public boolean isShouldStopSending() {
        return shouldStopSending;
    }

    public void setShouldStopSending(boolean shouldStopSending) {
        this.shouldStopSending = shouldStopSending;
    }
}
